#include "GameObj.h"
#include "util.h"
#include "SoundMgr.h"
#include "Game.h"
#include <string>
#include "Config.h"

//enum ObjType{OT_BLOCK=1,OT_BIRD,OT_PIG,OT_GROUND};
char *objTypeToString[_OBJ_TYPE_NUM]={
	"error object","block","bird","pig","ground"
};


GameObj::~GameObj(void)
{
}

const OgreNewt::MaterialID *GameObj::materialID=0;

int GameObj::getHealthPoint() const
{
	return _healthPoint;
}

void GameObj::setHealthPoint( int val )
{
	_healthPoint=val;
}

Ogre::Vector3 GameObj::getPosition()
{
	return body->getPosition();
}

void GameObj::init( Ogre::Vector3& size, Ogre::Vector3& pos, Ogre::Quaternion& orient)
{

	setHealthPoint(Config::parseInt(Config::getInstance()->getParam(getName()+"hp")));

	//get the global variables
	Game* game = Game::getInstance();
	Ogre::SceneManager * mSceneMgr = game->mSceneMgr;

	//init entity
	//static int count = 1;
	char buf[30]="GameObj";
	itoa(getID(),buf+7,10);
	entity = mSceneMgr->createEntity(buf, getMeshName());
	char* tmn=0;
	if(tmn=getMaterialName())
		entity->setMaterialName(tmn);
	//LOGVALUE(buf);
	//init sceneNode
	sceneNode = mSceneMgr->getRootSceneNode()->createChildSceneNode();
	sceneNode->attachObject(entity);
	sceneNode->setScale(size);

	// create collsion
	OgreNewt::ConvexCollisionPtr col = OgreNewt::ConvexCollisionPtr(new OgreNewt::CollisionPrimitives::ConvexHull( game->mWorld, entity ));
	body = new OgreNewt::Body( game->mWorld, col, getType() );
#ifdef OGRENEWT_NO_COLLISION_SHAREDPTR
	delete col;
#endif

	//set mass and center of mass
	Ogre::Vector3 interia,offset;
	col->calculateInertialMatrix(interia, offset);
	body->setMassMatrix( getMass(),getMass() * interia);
	body->setCenterOfMass(offset);
	body->attachNode( sceneNode );
	body->setStandardForceCallback();
	if (dynamic_cast<Bird*>(this)) {
		body->removeForceAndTorqueCallback();
	}
	body->setMaterialGroupID(getMaterialID());

#ifndef OGRENEWT_NO_OGRE_ANY
	body->setUserData( Ogre::Any((GameObj*)this) );
#else
	mBody->setUserData( this );
#endif

	//set position and orientation
	body->setPositionOrientation( pos, orient );
	sceneNode->setPosition( pos );
	sceneNode->setOrientation( orient );


	//log
	LOG(std::string("A ")+ objTypeToString[getType()]+std::string(" is created."));
}

const OgreNewt::MaterialID* GameObj::getMaterialID()
{
	ASSERT(materialID!=0);
	return materialID;
}

const std::string GameObj::getName() const
{
	return std::string(objTypeToString[getType()]);
}

GameObj::GameObj( void )
{
	_id=_idCnt++;
	
}

int GameObj::_idCnt=0;
